/*
 * FlashConsole - a little console that can do semi-useful debug stuff
 *
 * Copyright 2007 James W. Hofmann
 *
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package flash3f;

import flash.events.KeyboardEvent;
import flash.Lib;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;

class FlashConsole
{

	public var data : TextField;
	public var output : TextField;

	public var dict : Dynamic;
	
	public function new(mydict : Dynamic)
	{
		dict = mydict;
	
		Lib.current.stage.addEventListener(flash.events.KeyboardEvent.KEY_DOWN, keydown);
		data = new TextField();
		var format : TextFormat = new TextFormat();
		format.color = 0x00FFFF;
		format.align = TextFormatAlign.RIGHT;
		format.size = 24;
		data.defaultTextFormat = format;
		data.x = 4;
		data.y = 4;
		data.autoSize = TextFieldAutoSize.LEFT;
		data.type = TextFieldType.INPUT;
		data.text = "";
		data.restrict = "";
		data.visible= false;
		Lib.current.stage.addChild(data);

		output = new TextField();
		var format : TextFormat = new TextFormat();
		format.color = 0xFFFF00;
		format.align = TextFormatAlign.RIGHT;
		format.size = 24;
		output.defaultTextFormat = format;
		output.x = 4;
		output.y = 30;
		output.autoSize = TextFieldAutoSize.LEFT;
		output.type = TextFieldType.DYNAMIC;
		output.text = "";
		output.restrict = "";
		output.visible= false;
		Lib.current.stage.addChild(output);
		}
	
	public function keydown(evt: KeyboardEvent)
	{

		data.restrict = null;
	
		if (evt.charCode=="`".charCodeAt(0))
		{
			data.visible = !data.visible;
			output.visible = data.visible;
			if (data.visible)
			{
				Lib.current.stage.focus = data;
				data.text = "";
				data.restrict = "";
			}
		}

		if (evt.charCode==13 && data.visible) // CR
		{
			try
			{
				var args = data.text.split(",");
				Reflect.setField(Reflect.field(dict,args[0]),args[1],args[2]);
			}
			catch(foo : Dynamic)
			{
				output.text=foo;
			}
			data.text = "";
		}
		
	}

}
